package com.gewu.pm.ui.fragment.home;

import android.app.DatePickerDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.bean.ClockInStatisticsBean;
import com.gewu.pm.ui.adapter.home.ExpandableClockInAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 打卡报表-每日汇总
 */
public final class DailySummaryFragment extends AppFragment<AppActivity> {

    private ImageView mDatePrev;
    private TextView mSelectedDate;
    private ImageView mDateNext;
    private RecyclerView mRecyclerView;

    private ExpandableClockInAdapter mAdapter;
    private Calendar mCurrentDate;
    private SimpleDateFormat mDateFormat;
    private SimpleDateFormat mYearDateFormat;

    public static DailySummaryFragment newInstance() {
        return new DailySummaryFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_daily_summary;
    }

    @Override
    protected void initView() {
        mDatePrev = findViewById(R.id.iv_date_prev);
        mSelectedDate = findViewById(R.id.tv_selected_date);
        mDateNext = findViewById(R.id.iv_date_next);
        mRecyclerView = findViewById(R.id.rv_clock_in_list);

        // 初始化日期格式化器
        mDateFormat = new SimpleDateFormat("MM-dd E", Locale.getDefault());
        mYearDateFormat = new SimpleDateFormat("yyyy-MM-dd E", Locale.getDefault());
        
        // 初始化当前日期
        mCurrentDate = Calendar.getInstance();

        // 设置RecyclerView
        setupRecyclerView();

        // 设置点击事件
        setOnClickListener(mDatePrev, mSelectedDate, mDateNext);
    }

    @Override
    protected void initData() {
        // 更新日期显示
        updateDateDisplay();
        
        // 加载数据
        loadClockInData();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_date_prev) {
            // 日期减1天
            mCurrentDate.add(Calendar.DAY_OF_MONTH, -1);
            updateDateDisplay();
            loadClockInData();
        } else if (id == R.id.tv_selected_date) {
            // 显示日期选择器
            showDatePicker();
        } else if (id == R.id.iv_date_next) {
            // 日期加1天
            mCurrentDate.add(Calendar.DAY_OF_MONTH, 1);
            updateDateDisplay();
            loadClockInData();
        }
    }

    /**
     * 设置RecyclerView
     */
    private void setupRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new ExpandableClockInAdapter(getContext());
        
        // 设置数据变化监听器
        mAdapter.setOnDataChangeListener(() -> {
            // Fragment 自己管理数据变化
        });
        
        // 将Adapter绑定到RecyclerView（只需要设置一次，建立连接关系）
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 显示日期选择器
     */
    private void showDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
            getContext(),
            (view, year, month, dayOfMonth) -> {
                mCurrentDate.set(year, month, dayOfMonth);
                updateDateDisplay();
                loadClockInData();
            },
            mCurrentDate.get(Calendar.YEAR),
            mCurrentDate.get(Calendar.MONTH),
            mCurrentDate.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    /**
     * 更新日期显示
     */
    private void updateDateDisplay() {
        Calendar today = Calendar.getInstance();
        boolean isCurrentYear = mCurrentDate.get(Calendar.YEAR) == today.get(Calendar.YEAR);
        
        String dateText;
        if (isCurrentYear) {
            // 今年显示：月-日 周几
            dateText = mDateFormat.format(mCurrentDate.getTime());
        } else {
            // 非今年显示：年-月-日 周几
            dateText = mYearDateFormat.format(mCurrentDate.getTime());
        }
        
        mSelectedDate.setText(dateText);
    }

    /**
     * 加载打卡数据
     */
    private void loadClockInData() {
        // Fragment 自己创建测试数据（以后改为接口请求）
        ClockInStatisticsBean statistics = createTestData();
        
        // 将具体的业务数据传递给Adapter进行展示
        // 这里是设置列表的具体内容：分组（迟到、早退、旷工）和每组下的员工列表
        // 每次数据变化（如切换日期）都需要重新调用此方法更新显示内容
        mAdapter.setClockInData(statistics);
    }

    /**
     * 创建测试数据
     */
    private ClockInStatisticsBean createTestData() {
        ClockInStatisticsBean statistics = new ClockInStatisticsBean();
        statistics.setLateCount(3);
        statistics.setEarlyLeaveCount(3);
        statistics.setAbsentCount(2);
        
        // 创建测试员工数据
        statistics.setLateList(createTestEmployeeList("迟到", 3));
        statistics.setEarlyLeaveList(createTestEmployeeList("早退", 3));
        statistics.setAbsentList(createTestEmployeeList("旷工", 2));
        
        return statistics;
    }
    
    /**
     * 创建测试员工列表
     */
    private List<ClockInStatisticsBean.EmployeeClockInBean> createTestEmployeeList(String groupName, int count) {
        List<ClockInStatisticsBean.EmployeeClockInBean> employees = new ArrayList<>();
        String[] names = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"};
        
        for (int i = 0; i < count; i++) {
            ClockInStatisticsBean.EmployeeClockInBean employee =  new ClockInStatisticsBean.EmployeeClockInBean();
            employee.setEmployeeId("EMP" + String.format("%03d", i + 1));
            employee.setEmployeeName(names[i % names.length]);
            employees.add(employee);
        }
        
        return employees;
    }

    /**
     * 刷新数据（供外部调用）
     */
    public void refreshData() {
        loadClockInData();
    }

    /**
     * 设置日期（供外部调用）
     */
    public void setDate(Calendar date) {
        if (date != null) {
            mCurrentDate = (Calendar) date.clone();
            updateDateDisplay();
            loadClockInData();
        }
    }

    /**
     * 获取当前选择的日期
     */
    public Calendar getCurrentDate() {
        return (Calendar) mCurrentDate.clone();
    }
}
